﻿using System.Text.Json.Serialization;
using Core.Caching;
using Core.Helpers;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.Menus.Caching;
using Core.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Menus.Features.Commands.BatchDelete;

/// <summary>
/// 删除菜单
/// </summary>
public class BatchDeleteMenuCommand : ICacheInvalidatorRequest<Result<bool>>
{
    /// <summary>
    /// 删除的菜单ID集合
    /// </summary>
    public required List<Guid> MenuIds { get; set; }

    [JsonIgnore]
    public string CacheKey => MenusCacheKey.GetAllCacheKey;

    [JsonIgnore]
    public IEnumerable<string>? Tags => MenusCacheKey.Tags;
}

public class BatchDeleteMenuCommandHandler(IIdentityDbContext dbContext) : IRequestHandler<BatchDeleteMenuCommand, Result<bool>>
{

    public async Task<Result<bool>> Handle(BatchDeleteMenuCommand request, CancellationToken cancellationToken)
    {
        var menus = await dbContext.Permissions.Where(x => request.MenuIds.Contains(x.Id)).ToListAsync(cancellationToken);
        ExceptionHelper.ThrowIfTrue(menus == null || !menus.Any(), "数据不存在");

        var existChildNode = await dbContext.Organizations
            .AsNoTracking()
            .AnyAsync(x => request.MenuIds.Contains(x.ParentId!.Value), cancellationToken);
        ExceptionHelper.ThrowIfTrue(existChildNode, "存在子节点，无法删除");

        dbContext.Permissions.RemoveRange(menus!);
        var result = await dbContext.SaveChangesAsync(cancellationToken) > 0;

        return await Result<bool>.SucceedAsync(result, result, ["删除失败"]);
    }
}
